package main

import (
	"fmt"
	"login-server/config"
	"login-server/controller"
	"login-server/middleware"
	"login-server/model"

	"github.com/gin-gonic/gin"
)

func main() {
	// 加载配置文件
	if err := config.LoadConfig("config.yaml"); err != nil {
		panic(fmt.Sprintf("Error loading config: %v", err))
	}

	// 设置gin模式
	gin.SetMode(config.GlobalConfig.Server.Mode)

	// 初始化数据库
	config.InitDB()

	// 自动迁移数据库表
	config.DB.AutoMigrate(&model.User{})

	// 创建路由
	r := gin.Default()

	// CORS 中间件移到这里，在注册路由之前
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	userController := controller.NewUserController()

	// 公开路由
	r.POST("/register", userController.Register)
	r.POST("/login", userController.Login)

	// 需要认证的路由
	auth := r.Group("/api")
	auth.Use(middleware.AuthMiddleware())
	{
		auth.GET("/user/info", userController.GetUserInfo)
	}

	// 启动服务器
	addr := fmt.Sprintf(":%d", config.GlobalConfig.Server.Port)
	r.Run(addr)
}
